package com.ruoyi.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.SysUserVO;
import com.ruoyi.system.enums.AssessmentStatus;
import com.ruoyi.system.mapper.AssessMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static com.ruoyi.common.core.text.CharsetKit.UTF_8;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-22
 */
@Service
public class AssessServiceImpl implements IAssessService {
    @Autowired
    private AssessMapper assessMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IAssessUserService assessUserService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IAssessTableService assessTableService;
    @Autowired
    private IReportComprehensiveService reportComprehensiveService;
    @Autowired
    private IReportAssessTableService reportAssessTableService;
    @Autowired
    private IWarnUserLogService warnUserLogService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public Assess selectAssessById(Long id) {
        return assessMapper.selectAssessById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param assess 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<Assess> selectAssessList(Assess assess) {
        return assessMapper.selectAssessList(assess);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param assess 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAssess(Assess assess) {
        List<SysUser> userList = new ArrayList<>();
        Set<String> ancestors = new LinkedHashSet<>();
        //按用户
        if (StringUtils.isNotEmpty(assess.getCreateUser())) {
            String[] ids = assess.getCreateUser().split(",");
            for (String str : ids) {
                SysUser sysUser = sysUserService.selectUserById(Long.parseLong(str));
                SysDept sysDept = sysDeptService.selectDeptById(sysUser.getDeptId());
                userList.add(sysUser);
                if (sysDept != null) {
                    ancestors.addAll(Arrays.asList(sysDept.getAncestors().split(",")));
                    ancestors.add(sysDept.getDeptId().toString());
                }
            }
        } else {
            //按部门
            String[] ids = assess.getCreateDept().split(",");
            List<SysDept> sysDepts = new ArrayList<>();
            for (String str : ids) {
                sysDepts.add(sysDeptService.selectDeptById(Long.parseLong(str)));
            }
            //找本部门以及本部门下的所有部门
            List<Long> depeIds = new ArrayList<>();
            for (SysDept dept : sysDepts) {
                depeIds.add(dept.getDeptId());
                ancestors.add(dept.getDeptId().toString());
                ancestors.addAll(Arrays.asList(dept.getAncestors().split(",")));
                SysDept sysDept = new SysDept();
                sysDept.setParentId(dept.getDeptId());
                List<SysDept> childs = sysDeptService.selectDeptListByParentId(sysDept);
                if (!childs.isEmpty()) {
                    getDeptIds(childs, depeIds, ancestors);
                }
            }
            //获取学生教师角色
            Map<String, Long> map = new HashMap<>();
            map.put("学生", 3L);
            map.put("教师", 2L);
            JSONArray jsonArray = JSON.parseArray(assess.getOpenTarget());
            List<Long> roleIds = new ArrayList<>();
            for (Object object : jsonArray) {
                String open = (String) object;
                roleIds.add(map.get(open));
            }
            userList = sysUserService.selectAssessUserList(depeIds, roleIds);
        }

        if (userList.isEmpty()) {
            throw new ServiceException("该节点下未找到用户信息，请重新选择");
        }

        //创建任务
        assess.setStatus(determineTaskStatus(assess));
        assess.setCreateTime(new Date());
        // 转换为逗号分隔的字符串
//        String distinctAncestors = String.join(",", ancestors);
//        assess.setTaskDeptIds(distinctAncestors);
        // assess.setTaskDeptIds();
        assessMapper.insertAssess(assess);

        //创建任务和用户的关系
        AssessUser assessUser = new AssessUser();
        for (SysUser sysUser : userList) {
            assessUser.setTaskId(assess.getId());
            assessUser.setStatus(0);
            assessUser.setTaskName(assess.getTaskName());
            assessUser.setTaskUser(sysUser.getUserId());
            assessUserService.insertAssessUser(assessUser);
        }
        return userList.size();
    }

    @Override
    public int determineTaskStatus(Assess assess) {
        Date now = new Date();
        Date startTime = DateUtils.parseDate(assess.getStartTime());
        Date endTime = DateUtils.parseDate(assess.getEndTime());

        if (now.before(startTime)) {
            return 0; // 未开始
        } else if (now.after(endTime)) {
            return 2; // 已完成
        } else {
            return 1; // 进行中
        }
    }

    private void getDeptIds(List<SysDept> childs, List<Long> ids, Set<String> ancestors) {
        for (SysDept sysDept : childs) {
            ids.add(sysDept.getDeptId());
            ancestors.add(sysDept.getDeptId().toString());
            ancestors.addAll(Arrays.asList(sysDept.getAncestors().split(",")));
            SysDept sysDept1 = new SysDept();
            sysDept1.setParentId(sysDept.getDeptId());
            List<SysDept> childs1 = sysDeptService.selectDeptListByParentId(sysDept1);
            if (!childs1.isEmpty()) {
                getDeptIds(childs1, ids, ancestors);
            }
        }
    }


    /**
     * 修改【请填写功能名称】
     *
     * @param assess 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAssess(Assess assess) {
        return assessMapper.updateAssess(assess);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAssessByIds(Long[] ids) {
        return assessMapper.deleteAssessByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAssessById(Long id) {
        return assessMapper.deleteAssessById(id);
    }

    @Override
    @Transactional
    public String editAssess(AssessDTO assessDTO) {
        Assess assess = assessMapper.selectAssessById(assessDTO.getId());
        if (assess.getStatus() == 1) {  //进行中
            assess.setIsOpen(assessDTO.getIsOpen());
            assess.setTaskName(assessDTO.getTaskName());
            updateAssess(assess);
            return "该任务正在进行中，只帮您修改了基本信息";
        } else if (assess.getStatus() == 0) {  //未开始
            LoginUser loginUser = getLoginUser();
            Assess assessNew = new Assess();
            BeanUtils.copyProperties(assessDTO, assessNew);
            assessNew.setScaleIds(JSON.toJSONString(assessDTO.getScaleIdList()));
            assessNew.setOpenTarget(JSON.toJSONString(assessDTO.getOpenTargetList()));
            assessNew.setTaskCreator(loginUser.getUserId().toString());
            assessUserService.deleteAssessUserByTaskId(assessDTO.getId());
            assessMapper.deleteAssessById(assessDTO.getId());
            insertAssess(assessNew);
        }
        throw new ServiceException("该任务已完成，无法修改");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int commitAssess(CommitAssessDTO assessDTO) {
        if (assessDTO.getTaskId() == null) {
            throw new ServiceException("任务号不能为空");
        }
        Assess assess = assessMapper.selectAssessById(assessDTO.getTaskId());
        if (assess == null) {
            throw new ServiceException("未找到任务");
        }
        int status = determineTaskStatus(assess);
        if (status == 0) {
            throw new ServiceException("任务未开始，请耐心等待");
        } else if (status == 2) {
            throw new ServiceException("任务已结束");
        }

        LoginUser loginUser = getLoginUser();
        Map<Long, String> map = assessDTO.getCommitQuestion();
        for (Long qMap : map.keySet()) {
            Question question = new Question();
            question.setCommitUser(loginUser.getUserId());
            question.setTaskId(assessDTO.getTaskId());
            question.setScaleId(qMap);
            question.setCommitQuestion(map.get(qMap));
            question.setCommitTime(new Date());
            question.setStartQuestionTime(DateUtils.parseDate(assessDTO.getStartQuestionTime()));
            questionService.insertQuestion(question);
        }

        AssessUser assessUser = new AssessUser();
        assessUser.setTaskId(assessDTO.getTaskId());
        List<AssessUser> assessUsers = assessUserService.selectAssessUserList(assessUser);
        for (AssessUser assessU : assessUsers) {
            if (Objects.equals(assessU.getTaskUser(), loginUser.getUserId())) {
                assessU.setStatus(1);
                assessU.setCompleteTime(new Date());
                assessUserService.updateAssessUser(assessU);
            }
        }
        Question question = new Question();
        question.setTaskId(assessDTO.getTaskId());
        List<Question> questions = questionService.selectQuestionList(question);
        //完成任务
        if (assessUsers.size() == questions.size()) {
            assess.setStatus(2);
        }

        int i = updateAssess(assess);
        if (i > 0) {
            //生成报告
            ReportStudentDTO reportStudentDTO = new ReportStudentDTO();
            reportStudentDTO.setUserId(loginUser.getUserId());
            reportStudentDTO.setTaskId(assessDTO.getTaskId());
            generateReportInfo(reportStudentDTO);
        }
        return updateAssess(assess);
    }

    @Override
    public void exportTaskOverview(HttpServletResponse response, Long taskId) {
        try {
            Assess assess = selectAssessById(taskId);
            if (assess == null) {
                throw new ServiceException("未找到该任务");
            }

            List<List<String>> headList = Arrays.asList(
                            "序号",
                            "用户编号",
                            "提交答卷时间",
                            "用时",
                            "学校",
                            "年纪",
                            "班级",
                            "所属区域",
                            "姓名",
                            "学号",
                            "性别",
                            "任务完成情况"
                    ).stream()
                    .map(Collections::singletonList)
                    .collect(Collectors.toCollection(ArrayList::new));

            AssessUser assessUserDTO = new AssessUser();
            assessUserDTO.setTaskId(taskId);
            List<AssessUser> assessUsers = assessUserService.selectAssessUserList(assessUserDTO);
            List<List<String>> fixedData = IntStream.range(0, assessUsers.size())
                    .mapToObj(i -> {
                        AssessUser assessUser = assessUsers.get(i);
                        SysUserVO sysUser = sysUserService.selectUserVoById(assessUser.getTaskUser());

                        // 使用局部变量保持代码块清晰
                        Map<String, Object> map = questionService.selectQuestionCommitTime(taskId, assessUser.getTaskUser());
                        String duration = "";
                        String commitTime = "";
                        if (map != null && !map.isEmpty()) {
                            commitTime = map.get("commit_time").toString();
                            String startQuestionTime = map.get("start_question_time").toString();
                            Date commitTimeDate = DateUtils.parseDate(commitTime);
                            duration = calculateDuration(startQuestionTime, commitTimeDate); // 提取耗时计算方法
                        }

                        return Arrays.asList(
                                String.valueOf(i + 1),                                   // 序号
                                String.valueOf(sysUser.getUserId()),                                       //用户编号
                                commitTime,
                                duration,                                                // 用时（已封装计算）
                                sysUser.getSchool(),                                     // 学校
                                sysUser.getGrade(),                                      // 年级
                                sysUser.getClassz(),                                     // 班级
                                formatRegion(sysUser.getCity(), sysUser.getRegion()),    // 格式化区域
                                sysUser.getNickName(),                                   // 姓名
                                "",                                                      // 学号（默认空）
                                parseGender(sysUser.getSex()),                           // 性别解析
                                parseCompletionStatus(assessUser.getStatus())            // 任务状态解析
                        );
                    })
                    .collect(Collectors.toList());


            JSONArray scaleIds = (JSONArray) JSON.parse(assess.getScaleIds());


            List<List<String>> dataLists = new ArrayList<>();
            for (Object object : scaleIds) {
                Long scaleId = Long.parseLong(object.toString());
                AssessTable assessTable = assessTableService.selectAssessTableById(scaleId);
                JSONArray jsonArray = (JSONArray) JSON.parse(assessTable.getQuestionIds());
                for (Object object1 : jsonArray) {
                    List<String> heads = new ArrayList<>();
                    JSONObject jsonObject = (JSONObject) object1;
                    String name = jsonObject.getString("name");
                    heads.add(name);
                    headList.add(heads);
                }
            }


            //拼接数据
            for (List<String> fixed : fixedData) {
                List<String> dataList = new ArrayList<>();
                dataList.addAll(fixed);
                Long userId = Long.valueOf(fixed.get(1));
                for (Object object : scaleIds) {
                    Long scaleId = Long.parseLong(object.toString());
                    Question question = new Question();
                    question.setTaskId(taskId);
                    question.setScaleId(scaleId);
                    question.setCommitUser(userId);
                    List<Question> questionList = questionService.selectQuestionList(question);
                    if (!questionList.isEmpty()) {
                        Question questionData = questionList.get(0);
                        JSONObject jsonObject = (JSONObject) JSON.parse(questionData.getCommitQuestion());
                        JSONArray questions = jsonObject.getJSONArray("questions");
                        for (Object object1 : questions) {
                            JSONObject questionObj = (JSONObject) object1;
                            //String name = questionObj.getString("answer");
                            String score = questionObj.getString("score");
                            dataList.add(score);
                        }
                    }
                }
                dataLists.add(dataList);
            }

            // 设置响应内容类型为 Excel 文件
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 设置响应字符编码
            response.setCharacterEncoding(UTF_8);
            // 使用 URLEncoder 编码文件名，防止中文乱码
            String fileNameEncode = URLEncoder.encode("assess", UTF_8).replaceAll("\\+", "%20");
            // 设置响应头，告诉浏览器这是一个附件
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEncode + ".xlsx");
            EasyExcel.write(response.getOutputStream()).head(headList).sheet(assess.getTaskName())
                    .doWrite(dataLists);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // 提取的工具方法
    private String calculateDuration(String startTime, Date commitTime) {
        return Optional.ofNullable(commitTime)
                .map(eTime -> {
                    Date sTime = DateUtils.parseDate(startTime);
                    long seconds = (eTime.getTime() - sTime.getTime()) / 1000;
                    return seconds + "秒";
                })
                .orElse("");
    }

    private String formatRegion(String city, String region) {
        return Stream.of(city, region)
                .filter(Objects::nonNull)
                .collect(Collectors.joining("-"));
    }

    private String parseGender(String sex) {
        return "0".equals(sex) ? "男" : "女";
    }

    private String parseCompletionStatus(int status) {
        return status == 0 ? "未填写" : "已填写";
    }


    @Override
    public void generateReportInfo(ReportStudentDTO reportStudentDTO) {

        SysUser sysUser = sysUserService.selectUserById(reportStudentDTO.getUserId());
        if (sysUser == null) {
            throw new ServiceException("未找到用户信息");
        }
        Assess assess = selectAssessById(reportStudentDTO.getTaskId());
        if (assess == null) {
            throw new ServiceException("未找到任务信息");
        }

        Question question = new Question();
        question.setTaskId(assess.getId());
        question.setCommitUser(sysUser.getUserId());
        List<Question> questionList = questionService.selectQuestionList(question);
        if (!checkQuestion(questionList)) {
            //throw new ServiceException("此次任务没有【抑郁】指标");
            //此次任务没有【抑郁】指标，不在生成报告
            return;
        }

        List<ReportAssessTable> activeList = new ArrayList<>();
        List<ReportAssessTable> negativeList = new ArrayList<>();
        for (Question question1 : questionList) {
            AssessTable assessTable = assessTableService.selectAssessTableById(question1.getScaleId());
            //获取用户提交的问卷
            JSONObject commitQuestion = JSONObject.parseObject(question1.getCommitQuestion());
            //获取当前指标的总数
            Double totalScore = commitQuestion.getDouble("totalScore");
            //题目总数
            JSONArray jsonArray = commitQuestion.getJSONArray("questions");
            //平均分
            if (assessTable.getPointsType() == 1) {
                totalScore = totalScore / jsonArray.size();
            }
            //用总数判断指标等级
            JSONObject levelObj = getLevelByTaskLevel(totalScore, assessTable.getTaskLevelIds(), assessTable.getType());
            ReportAssessTable reportAssessTable = new ReportAssessTable();
            reportAssessTable.setTaskId(reportStudentDTO.getTaskId());
            reportAssessTable.setUserId(reportStudentDTO.getUserId());
            reportAssessTable.setAssessTableName(assessTable.getEvaluation());
            reportAssessTable.setAssessTableId(assessTable.getId());
            reportAssessTable.setAssessTableType(Long.valueOf(assessTable.getType()));
            reportAssessTable.setCheck(levelObj.getBoolean("check") ? 1L : 0L);
            reportAssessTable.setLevel(levelObj.getString("level"));
            reportAssessTable.setName(levelObj.getString("name"));
            reportAssessTable.setNewLevel(levelObj.getString("newLevel"));
            reportAssessTable.setDetail(levelObj.getString("detail"));
            reportAssessTable.setCreateTime(new Date());
            if (assessTable.getType() == 1) {   //积极指标
                activeList.add(reportAssessTable);
            } else if (assessTable.getType() == 2) {  //消极指标
                negativeList.add(reportAssessTable);
                //抑郁指标，第九题为自伤
                if ("PHQ-9".equals(assessTable.getShortName())) {
                    ReportAssessTable phq9 = getPHQ9(jsonArray);
                    phq9.setTaskId(reportStudentDTO.getTaskId());
                    phq9.setUserId(reportStudentDTO.getUserId());
                    phq9.setAssessTableId(-assessTable.getId());
                    negativeList.add(phq9);
                }
            }
        }

        //综合测评报告
        List<ReportAssessTable> allList = new ArrayList<>();
        allList.addAll(activeList);
        allList.addAll(negativeList);

        //保存指标数据
        reportAssessTableService.insertReportAssessTableList(allList);


        List<ReportComprehensive> list = new ArrayList<>();
        for (AssessmentStatus status : AssessmentStatus.values()) {
            ReportComprehensive reportComprehensive = new ReportComprehensive();
            reportComprehensive.setTaskId(reportStudentDTO.getTaskId());
            reportComprehensive.setUserId(reportStudentDTO.getUserId());
            reportComprehensive.setCheck(0L);
            reportComprehensive.setName(status.getName());
            reportComprehensive.setCreateTime(new Date());
            list.add(reportComprehensive);
        }

        String text = getComprehensive(allList);
        for (ReportComprehensive map : list) {
            if (text.equals(map.getName())) {
                map.setCheck(1L);
            }
        }

        //保存评测数据
        reportComprehensiveService.insertReportComprehensiveList(list);

        //生成预警人员名单
        WarnUserLog warnUserLog = new WarnUserLog();
        warnUserLog.setTaskId(reportStudentDTO.getTaskId());
        warnUserLog.setUserId(reportStudentDTO.getUserId());
        warnUserLog.setWarnLevel(text);
        warnUserLog.setUserName(sysUser.getUserName());
        warnUserLog.setNickName(sysUser.getNickName());
        warnUserLog.setSex(Integer.parseInt(sysUser.getSex()));
        warnUserLog.setLevelJudge(1); //评测预警
        warnUserLog.setIsInterview(0);  //没有访谈
        warnUserLog.setCreateTime(new Date());
        SysUserVO sysUserVO = sysUserService.selectUserVoById(sysUser.getUserId());
        warnUserLog.setGrade(sysUserVO.getGradeId());
        warnUserLog.setClassz(sysUserVO.getClasszId());
        warnUserLog.setSchool(sysUserVO.getSchoolId());
        warnUserLogService.insertWarnUserLog(warnUserLog);
    }

    @Override
    public Map<String, Object> teamReportInfo(ReportTeamDTO reportTeacherDTO) {

        Map<String, Object> result = new HashMap<>();

        SysDept nowDept = sysDeptService.selectDeptById(Long.valueOf(reportTeacherDTO.getDeptId()));


        SysDept queryDept = new SysDept();
        queryDept.setParentId(nowDept.getDeptId());
        List<SysDept> sysDepts = sysDeptService.selectDeptListByParentId(queryDept);
        if (sysDepts.isEmpty() && nowDept.getType() == 6) {
            sysDepts.add(nowDept);
        }
        List<String> statusList = AssessmentStatus.list();
        List<Map<String, Object>> assessObjects = new ArrayList<>();
        List<Map<String, Object>> barChartCount = new ArrayList<>();
        List<Map<String, Object>> distributionCount = new ArrayList<>();
        int countUser = 0;
        for (SysDept sysDept : sysDepts) {
            List<Long> deptIds = sysDeptService.selectChildrenDeptIds(sysDept.getDeptId());
            if (deptIds.isEmpty()) {
                deptIds.add(sysDept.getDeptId());
            }
            Map<String, Object> mapCount = sysUserService.selectAssessUseReportCount(deptIds, reportTeacherDTO.getTaskId());
            mapCount.put("name", sysDept.getDeptName());
            countUser = countUser + Integer.parseInt(mapCount.get("count").toString());
            assessObjects.add(mapCount);
            //柱状图
            Map<String, Object> barMap = new HashMap<>();
            List<Map<String, Object>> barChartList = reportComprehensiveService.countChartByUser(statusList, deptIds, reportTeacherDTO.getTaskId());
            barMap.put("name", sysDept.getDeptName());
            barMap.put("data", barChartList);
            barChartCount.add(barMap);

            //每个下级心理健康分布
            Map<String, Object> distributionMap = new HashMap<>();
            List<Map<String, Object>> distributionList = reportAssessTableService.countCharByUser(countUser, deptIds, reportTeacherDTO.getTaskId());
            distributionMap.put("name", sysDept.getDeptName());
            distributionMap.put("data", distributionList);
            distributionCount.add(distributionMap);
        }
        result.put("assessObject", assessObjects);

        //饼图
        List<Long> deptIds = sysDeptService.selectChildrenDeptIds(nowDept.getDeptId());
        if (deptIds.isEmpty()) {
            deptIds.add(nowDept.getDeptId());
        }
        List<Map<String, Object>> pipChartCount = reportComprehensiveService.countChartByUser(statusList, deptIds, reportTeacherDTO.getTaskId());
        result.put("assessPipChart", pipChartCount);
        //柱状图
        result.put("assessBarChart", barChartCount);
        //学校整体心理健康水平总结
        List<Map<String, Object>> wholeCharts = reportAssessTableService.countCharByUser(countUser, deptIds, reportTeacherDTO.getTaskId());
        result.put("assessSchoolWholeChart", wholeCharts);
        //每个下级心理健康分布
        result.put("assessDistributionChart", distributionCount);
        //预警名单
        result.put("assessWarnList", getAssessWarnList(reportTeacherDTO.getTaskId()));
        //心理健康具体问题
        result.put("assessSpecificList", getAssessSpecificList(countUser, sysDepts, deptIds, wholeCharts, reportTeacherDTO, true));
        return result;
    }

    @Override
    public Map<String, Object> gradeClassReportInfo(ReportTeamDTO reportDTO) {

        Map<String, Object> result = new HashMap<>();
        //多个年级
        String[] deptIdArray = reportDTO.getDeptId().split(",");
        List<Long> nowDeptIdList = Arrays.stream(deptIdArray)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        List<SysDept> sysDepts = sysDeptService.selectDeptByDeptIds(nowDeptIdList, null);
        if (sysDepts.isEmpty()) {
            throw new ServiceException("年级不存在");
        }

        List<String> statusList = AssessmentStatus.list();
        List<Map<String, Object>> assessObjects = new ArrayList<>();
        List<Map<String, Object>> distributionCount = new ArrayList<>();
        List<Map<String, Object>> distributionOrderDesc = new ArrayList<>();
        int countUser = 0;
        for (SysDept sysDept : sysDepts) {
            List<Long> deptIds = sysDeptService.selectChildrenDeptIds(sysDept.getDeptId());
            if (deptIds.isEmpty()) {
                deptIds.add(sysDept.getDeptId());
            }
            Map<String, Object> mapCount = sysUserService.selectAssessUseReportCount(deptIds, reportDTO.getTaskId());
            mapCount.put("name", sysDept.getDeptName());
            countUser = countUser + Integer.parseInt(mapCount.get("count").toString());
            assessObjects.add(mapCount);

            //每个下级心理健康分布
            Map<String, Object> distributionMap = new HashMap<>();
            List<Map<String, Object>> distributionList = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
            distributionMap.put("name", sysDept.getDeptName());
            distributionMap.put("data", distributionList);
            distributionCount.add(distributionMap);

            //XX中学XX年级心理健康问题检出率从高到低依次排名的指标是：
            Map<String, Object> distributionDescMap = new HashMap<>();
            List<Map<String, Object>> distributionDescList = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
            distributionDescMap.put("name", sysDept.getDeptName());
            distributionDescMap.put("data", distributionDescList);
            distributionOrderDesc.add(distributionDescMap);
        }
        result.put("assessObject", assessObjects);

        //饼图
        List<Long> deptIds = new ArrayList<>();
        for (SysDept sysDept : sysDepts) {
            List<Long> childrenDeptIds = sysDeptService.selectChildrenDeptIds(sysDept.getDeptId());
            if (childrenDeptIds.isEmpty()) {
                deptIds.add(sysDept.getDeptId());
            } else {
                deptIds.addAll(childrenDeptIds);

            }
        }
        List<Map<String, Object>> pipChartCount = reportComprehensiveService.countChartByUser(statusList, deptIds, reportDTO.getTaskId());
        result.put("assessPipChart", pipChartCount);
        //学校整体心理健康水平总结
        List<Map<String, Object>> wholeCharts = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
        result.put("assessSchoolWholeChart", wholeCharts);
        //每个下级心理健康分布
        result.put("assessDistributionChart", distributionCount);
        //XX中学XX年级心理健康问题检出率从高到低依次排名的指标是：
        result.put("assessDistributionOrderDesc", distributionOrderDesc);
        //预警名单
        result.put("assessWarnList", getAssessWarnList(reportDTO.getTaskId()));
        //心理健康具体问题
        result.put("assessSpecificList", getAssessSpecificList(countUser, sysDepts, deptIds, wholeCharts, reportDTO, false));
        return result;
    }

    @Override
    public Map<String, Object> schoolReportInfo(ReportTeamDTO reportDTO) {

        Map<String, Object> result = new HashMap<>();
        SysDept nowDept = sysDeptService.selectDeptById(Long.valueOf(reportDTO.getDeptId()));
        SysDept queryDept = new SysDept();
        queryDept.setParentId(nowDept.getDeptId());
        List<SysDept> sysDepts = sysDeptService.selectDeptListByParentId(queryDept);
        if (sysDepts.isEmpty() && nowDept.getType() == 6) {
            sysDepts.add(nowDept);
        }
        List<String> statusList = AssessmentStatus.list();
        List<Map<String, Object>> assessObjects = new ArrayList<>();
        List<Map<String, Object>> barChartCount = new ArrayList<>();
        List<Map<String, Object>> distributionCount = new ArrayList<>();
        List<Map<String, Object>> distributionOrderDesc = new ArrayList<>();
        int countUser = 0;
        for (SysDept sysDept : sysDepts) {
            List<Long> deptIds = sysDeptService.selectChildrenDeptIds(sysDept.getDeptId());
            if (deptIds.isEmpty()) {
                deptIds.add(sysDept.getDeptId());
            }
            //饼图
            Map<String, Object> mapCount = sysUserService.selectAssessUseReportCount(deptIds, reportDTO.getTaskId());
            mapCount.put("name", sysDept.getDeptName());
            countUser = countUser + Integer.parseInt(mapCount.get("count").toString());
            assessObjects.add(mapCount);
            //柱状图
            Map<String, Object> barMap = new HashMap<>();
            List<Map<String, Object>> barChartList = reportComprehensiveService.countChartByUser(statusList, deptIds, reportDTO.getTaskId());
            barMap.put("name", sysDept.getDeptName());
            barMap.put("data", barChartList);
            barChartCount.add(barMap);

            //每个下级心理健康分布
            Map<String, Object> distributionMap = new HashMap<>();
            List<Map<String, Object>> distributionList = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
            distributionMap.put("name", sysDept.getDeptName());
            distributionMap.put("data", distributionList);
            distributionCount.add(distributionMap);

            //XX中学XX年级心理健康问题检出率从高到低依次排名的指标是：
            Map<String, Object> distributionDescMap = new HashMap<>();
            List<Map<String, Object>> distributionDescList = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
            distributionDescMap.put("name", sysDept.getDeptName());
            distributionDescMap.put("data", distributionDescList);
            distributionOrderDesc.add(distributionDescMap);
        }
        result.put("assessObject", assessObjects);

        //饼图
        List<Long> deptIds = sysDeptService.selectChildrenDeptIds(nowDept.getDeptId());
        if (deptIds.isEmpty()) {
            deptIds.add(nowDept.getDeptId());
        }
        List<Map<String, Object>> pipChartCount = reportComprehensiveService.countChartByUser(statusList, deptIds, reportDTO.getTaskId());
        result.put("assessPipChart", pipChartCount);

        //获取不同年级的心理健康整体情况-本次测查中
        List<ReportGradeDataDTO> gradeDataList = parseAssessBarChart(barChartCount);
        result.put("assessBarChartDetailPrediction", getBarChartDetailPrediction(gradeDataList));
        //柱状图
        result.put("assessBarChart", barChartCount);
        //不同年级学生的心理健康整体水平分布表
        result.put("assessBarChartDetailList", getBarChartDetailList(gradeDataList));
        //学校整体心理健康水平总结
        List<Map<String, Object>> wholeCharts = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
        result.put("assessSchoolWholeChart", wholeCharts);
        //每个下级心理健康分布
        result.put("assessDistributionChart", distributionCount);
        //XX中学XX年级心理健康问题检出率从高到低依次排名的指标是：
        result.put("assessDistributionOrderDesc", distributionOrderDesc);
        //预警名单
        result.put("assessWarnList", getAssessWarnList(reportDTO.getTaskId()));
        //心理健康具体问题
        result.put("assessSpecificList", getAssessSpecificList(countUser, sysDepts, deptIds, wholeCharts, reportDTO, true));
        return result;
    }

    @Override
    public Map<String, Object> regionReportInfo(ReportTeamDTO reportDTO) {
        //区域报告特殊，统计区域下学校的年级
        Map<String, Object> result = new HashMap<>();
        List<SysDept> sysDepts = sysDeptService.selectChildrenDeptIdList(Long.valueOf(reportDTO.getDeptId()), 5);
        Map<String, List<Long>> deptMap = new HashMap<>();
        for (SysDept sysDept : sysDepts) {
            List<Long> objMap = deptMap.get(sysDept.getDeptName());
            if (objMap != null && !objMap.isEmpty()) {
                objMap.add(sysDept.getDeptId());
            } else {
                List<Long> depts = new ArrayList<>();
                depts.add(sysDept.getDeptId());
                deptMap.put(sysDept.getDeptName(), depts);
            }
        }
        List<String> statusList = AssessmentStatus.list();
        List<Map<String, Object>> assessObjects = new ArrayList<>();
        List<Map<String, Object>> barChartCount = new ArrayList<>();
        List<Map<String, Object>> distributionCount = new ArrayList<>();
        List<Map<String, Object>> distributionOrderDesc = new ArrayList<>();
        int countUser = 0;
        for (String key : deptMap.keySet()) {
            List<Long> deptLists = deptMap.get(key);
            List<Long> deptIds = new ArrayList<>();
            for (Long l : deptLists) {
                deptIds.addAll(sysDeptService.selectChildrenDeptIds(l));
            }
            //饼图
            Map<String, Object> mapCount = sysUserService.selectAssessUseReportCount(deptIds, reportDTO.getTaskId());
            mapCount.put("name", key);
            countUser = countUser + Integer.parseInt(mapCount.get("count").toString());
            assessObjects.add(mapCount);
            //柱状图
            Map<String, Object> barMap = new HashMap<>();
            List<Map<String, Object>> barChartList = reportComprehensiveService.countChartByUser(statusList, deptIds, reportDTO.getTaskId());
            barMap.put("name", key);
            barMap.put("data", barChartList);
            barChartCount.add(barMap);

            //每个下级心理健康分布
            Map<String, Object> distributionMap = new HashMap<>();
            List<Map<String, Object>> distributionList = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
            distributionMap.put("name", key);
            distributionMap.put("data", distributionList);
            distributionCount.add(distributionMap);

            //XX中学XX年级心理健康问题检出率从高到低依次排名的指标是：
            Map<String, Object> distributionDescMap = new HashMap<>();
            List<Map<String, Object>> distributionDescList = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
            distributionDescMap.put("name", key);
            distributionDescMap.put("data", distributionDescList);
            distributionOrderDesc.add(distributionDescMap);
        }
        result.put("assessObject", assessObjects);

        //饼图
        List<Long> deptIds = new ArrayList<>();
        for (String key : deptMap.keySet()) {
            List<Long> deptLists = deptMap.get(key);
            for (Long l : deptLists) {
                deptIds.addAll(sysDeptService.selectChildrenDeptIds(l));
            }
        }
        List<Map<String, Object>> pipChartCount = reportComprehensiveService.countChartByUser(statusList, deptIds, reportDTO.getTaskId());
        result.put("assessPipChart", pipChartCount);

        //获取不同年级的心理健康整体情况-本次测查中
        List<ReportGradeDataDTO> gradeDataList = parseAssessBarChart(barChartCount);
        result.put("assessBarChartDetailPrediction", getBarChartDetailPrediction(gradeDataList));
        //柱状图
        result.put("assessBarChart", barChartCount);
        //不同年级学生的心理健康整体水平分布表
        result.put("assessBarChartDetailList", getBarChartDetailList(gradeDataList));
        //学校整体心理健康水平总结
        List<Map<String, Object>> wholeCharts = reportAssessTableService.countCharByUser(countUser, deptIds, reportDTO.getTaskId());
        result.put("assessSchoolWholeChart", wholeCharts);
        //每个下级心理健康分布
        result.put("assessDistributionChart", distributionCount);
        //XX中学XX年级心理健康问题检出率从高到低依次排名的指标是：
        result.put("assessDistributionOrderDesc", distributionOrderDesc);
        //预警名单
        result.put("assessWarnList", getAssessWarnList(reportDTO.getTaskId()));
        //心理健康具体问题
        result.put("assessSpecificList", getAssessSpecificList(countUser, sysDepts, deptIds, wholeCharts, reportDTO, true));
        return result;
    }

    @Override
    public List<Assess> selectAssessListByStatus(List<Integer> statusList) {
        return assessMapper.selectAssessListByStatus(statusList);
    }

    //不同年级学生的心理健康整体水平分布表
    private JSONArray getBarChartDetailList(List<ReportGradeDataDTO> gradeDataList) {

        // 心理健康良好、一级预警、二级预警、三级预警
        List<String> statuses = AssessmentStatus.list();
        Map<String, List<ReportDataItemDTO>> statusData = new LinkedHashMap<>();
        // 初始化 statusData
        for (String status : statuses) {
            statusData.put(status, new ArrayList<>());
        }

        // 收集每个状态的数据
        for (ReportGradeDataDTO gradeData : gradeDataList) {
            for (String status : statuses) {
                ReportDataItemDTO dataItem = gradeData.getDataMap().get(status);
                if (dataItem != null) {
                    statusData.get(status).add(dataItem);
                }
            }
        }

        JSONObject result = new JSONObject();

        // 每个年级的数据
        JSONArray grades = new JSONArray();
        for (ReportGradeDataDTO gradeData : gradeDataList) {
            JSONObject grade = new JSONObject();
            grade.put("name", gradeData.getGradeName());

            JSONObject data = new JSONObject();
            for (String status : statuses) {
                ReportDataItemDTO dataItem = gradeData.getDataMap().get(status);
                if (dataItem != null) {
                    int total = gradeData.getTotalMan() + gradeData.getTotalWoman();
                    double ratio = (double) dataItem.getValue() / total * 100;
                    data.put(status, dataItem.getValue() + " (" + String.format("%.2f", ratio) + "%)");
                } else {
                    data.put(status, "");
                }
            }
            grade.put("data", data);
            grades.add(grade);
        }

        // 总计
        JSONObject total = new JSONObject();
        JSONObject totalResult = new JSONObject();
        for (String status : statuses) {
            int sumValue = statusData.get(status).stream().mapToInt(ReportDataItemDTO::getValue).sum();
            int sumTotal = gradeDataList.stream().mapToInt(gradeData -> gradeData.getTotalMan() + gradeData.getTotalWoman()).sum();
            double ratio = (double) sumValue / sumTotal * 100;
            total.put(status, sumValue + " (" + String.format("%.2f", ratio) + "%)");
        }
        totalResult.put("data", total);
        totalResult.put("name", "总计");
        grades.add(totalResult);

        // 对比
        JSONObject comparison = new JSONObject();
        JSONObject comparisonResult = new JSONObject();
        for (String status : statuses) {
            List<ReportDataItemDTO> dataItems = statusData.get(status);
            int maxIndex = IntStream.range(0, dataItems.size())
                    .boxed()
                    .max(Comparator.comparingInt(i -> dataItems.get(i).getValue()))
                    .orElse(-1);
            int minIndex = IntStream.range(0, dataItems.size())
                    .boxed()
                    .min(Comparator.comparingInt(i -> dataItems.get(i).getValue()))
                    .orElse(-1);

            Map<String, Object> map = new HashMap<>();
            if (maxIndex != -1 && minIndex != -1) {
                map.put("max", gradeDataList.get(maxIndex).getGradeName());
                map.put("min", gradeDataList.get(minIndex).getGradeName());
            } else {
                map.put("max", "");
                map.put("min", "");
            }
            comparison.put(status, map);
        }
        comparisonResult.put("data", comparison);
        comparisonResult.put("name", "对比");
        grades.add(comparisonResult);
        return grades;
    }

    //获取不同年级的心理健康整体情况-本次测查中
    private List<String> getBarChartDetailPrediction(List<ReportGradeDataDTO> gradeDataList) {
        List<String> statusList = AssessmentStatus.list();
        List<String> texts = new ArrayList<>();
        for (String status : statusList) {
            texts.add(analyzeStatus(gradeDataList, status));
        }
        return texts;
    }

    private List<ReportGradeDataDTO> parseAssessBarChart(List<Map<String, Object>> barChartCount) {
        List<ReportGradeDataDTO> gradeDataList = new ArrayList<>();
        for (int i = 0; i < barChartCount.size(); i++) {
            Map<String, Object> gradeObj = barChartCount.get(i);
            String gradeName = gradeObj.get("name").toString();
            List<Map<String, Object>> dataArr = (List<Map<String, Object>>) gradeObj.get("data");
            ;

            Map<String, ReportDataItemDTO> dataMap = new HashMap<>();
            int totalMan = 0, totalWoman = 0;
            for (int j = 0; j < dataArr.size(); j++) {
                Map<String, Object> dataObj = dataArr.get(j);
                String dataType = dataObj.get("data").toString();
                int value = Integer.parseInt(dataObj.get("value").toString());
                int man = Integer.parseInt(dataObj.get("man").toString());
                int woman = Integer.parseInt(dataObj.get("woman").toString());

                dataMap.put(dataType, new ReportDataItemDTO(value, man, woman));
                totalMan += man;
                totalWoman += woman;
            }
            gradeDataList.add(new ReportGradeDataDTO(gradeName, dataMap, totalMan, totalWoman));
        }
        return gradeDataList;
    }

    private String analyzeStatus(List<ReportGradeDataDTO> gradeDataList, String status) {
        double maxRatio = 0, minRatio = Double.MAX_VALUE;
        String maxGrade = "", minGrade = "";
        boolean isManHigher = true;

        for (ReportGradeDataDTO gradeData : gradeDataList) {
            ReportDataItemDTO dataItem = gradeData.getDataMap().get(status);
            if (dataItem == null) continue;

            double total = gradeData.getTotalMan() + gradeData.getTotalWoman();
            double ratio = (double) dataItem.getValue() / total * 100;

            if (ratio > maxRatio) {
                maxRatio = ratio;
                maxGrade = gradeData.getGradeName();
            }
            if (ratio < minRatio) {
                minRatio = ratio;
                minGrade = gradeData.getGradeName();
            }

            double manRatio = (double) dataItem.getMan() / gradeData.getTotalMan() * 100;
            double womanRatio = (double) dataItem.getWoman() / gradeData.getTotalWoman() * 100;
            isManHigher = manRatio > womanRatio;
        }
        String text = status + "比例：" + maxGrade + "最高，为 " + String.format("%.1f", maxRatio) + "%；" + minGrade + "最低，为 " + String.format("%.1f", minRatio) + "%。性别方面，" + (isManHigher ? "男生" : "女生") + "的" + status + "占比比" + (isManHigher ? "女生" : "男生") + "大。";
        return text;
    }

    private List<Map<String, Object>> getAssessWarnList(Long taskId) {
        WarnUserLog warnUserLog = new WarnUserLog();
        warnUserLog.setTaskId(taskId);
        warnUserLog.setWarnLevel(AssessmentStatus.WARNING_LEVEL_3.getName());
        List<WarnUserLog> warnUserLogs = warnUserLogService.selectWarnUserLogList(warnUserLog);
        List<Map<String, Object>> results = new ArrayList<>();
        for (WarnUserLog warn : warnUserLogs) {
            Map<String, Object> map = new HashMap<>();
            map.put("nickName", warn.getNickName());
            map.put("sex", warn.getSex());
            map.put("remark", warn.getWarnLevel());
            map.put("grade", warn.getGradeName());
            map.put("classz", warn.getClasszName());
            map.put("school", warn.getSchoolName());
            results.add(map);
        }
        return results;
    }

    private List<Map<String, Object>> getAssessSpecificList(int countUser, List<SysDept> sysDepts, List<Long> deptIds, List<Map<String, Object>> wholeCharts, ReportTeamDTO reportTeacherDTO, boolean next) {
        //心理健康具体问题
        List<Map<String, Object>> specificList = new ArrayList<>();
        for (Map<String, Object> wholeChart : wholeCharts) {
            if (wholeChart.get("tableId") == null) {
                return new ArrayList<>();
            }
            Long tableId = Long.parseLong(wholeChart.get("tableId").toString());
            Map<String, Object> specificMap = new HashMap<>();
            JSONArray jsonArray;
            //自伤自杀意念
            if (tableId == -167) {
                specificMap.put("name", "自伤自杀意念");
                specificMap.put("definition", "有结束自己生命或用某种方式伤害自己的念头");
                specificMap.put("assessType", 2);
                jsonArray = buildSelfHarmLevels();
            } else {
                //获取指标
                AssessTable assessTable = assessTableService.selectAssessTableById(tableId);
                specificMap.put("name", assessTable.getEvaluation());
                specificMap.put("definition", assessTable.getEvaluation() + "指的是" + assessTable.getNumber());
                specificMap.put("assessType", assessTable.getType());
                jsonArray = JSONArray.parseArray(assessTable.getTaskLevelIds()).stream()
                        .sorted(Comparator.comparingInt(e -> ((JSONObject) e).getIntValue("lowestScore")))
                        .collect(Collectors.toCollection(JSONArray::new));
            }
            specificMap.put("level", jsonArray);
            // 提取 name 字段组成新集合
            List<String> nameList = jsonArray.stream()
                    .map(obj -> ((JSONObject) obj).getString("name"))
                    .collect(Collectors.toList());

            //整体情况
            List<Map<String, Object>> pipCharts = reportAssessTableService.countTaskLevelCharByUser(deptIds, nameList, reportTeacherDTO.getTaskId(), tableId);
            specificMap.put("pipChart", pipCharts);

            if (next) {
                //每个下级的具体情况
                List<Map<String, Object>> pipList = new ArrayList<>();
                for (SysDept sysDept : sysDepts) {
                    Map<String, Object> pipMap = new HashMap<>();
                    List<Long> childIds = sysDeptService.selectChildrenDeptIds(sysDept.getDeptId());
                    if (childIds.isEmpty()) {
                        childIds.add(sysDept.getDeptId());
                    }
                    List<Map<String, Object>> childPipCharts = reportAssessTableService.countTaskLevelCharByUser(childIds, nameList, reportTeacherDTO.getTaskId(), tableId);
                    pipMap.put("data", childPipCharts);
                    pipMap.put("name", sysDept.getDeptName());
                    pipList.add(pipMap);
                }
                specificMap.put("pipList", pipList);
            }

            //总结
            specificMap.put("summary", getSummary(pipCharts, specificMap, countUser));

            specificList.add(specificMap);
        }
        return specificList;
    }

    private JSONArray buildSelfHarmLevels() {
        JSONArray array = new JSONArray();

        array.add(JSONObject.of(
                "detail", "通过测试得知该生无自伤自杀意念",
                "isLowestScore", false,
                "level", "正常",
                "lowestScore", 0,
                "name", "无自伤自杀意念"
        ));

        array.add(JSONObject.of(
                "detail", "通过测试得知该生有轻度自伤自杀意念",
                "isLowestScore", false,
                "level", "轻度",
                "lowestScore", 1,
                "name", "轻度自伤自杀意念"
        ));

        array.add(JSONObject.of(
                "detail", "通过测试得知该生有中度自伤自杀意念",
                "isLowestScore", false,
                "level", "中度",
                "lowestScore", 2,
                "name", "中度自伤自杀意念"
        ));

        array.add(JSONObject.of(
                "detail", "通过测试得知该生有重度自伤自杀意念",
                "isLowestScore", false,
                "level", "重度",
                "lowestScore", 3,
                "name", "重度自伤自杀意念"
        ));
        return array;
    }

    private String getSummary(List<Map<String, Object>> dataList, Map<String, Object> specificMap, int total) {
        if (total == 0) {
            return "本次测评中，没有相关数据。";
        }

        String name = specificMap.get("name").toString();
        // 1 积极 2 消极
        String type = specificMap.get("assessType").toString();

        // 按 name 分组统计 value
        Map<String, Integer> levelMap = dataList.stream()
                .collect(Collectors.toMap(
                        obj -> obj.get("name").toString(),
                        obj -> Integer.parseInt(obj.get("value").toString())
                ));

        // 性别判断：找出哪个性别占比较高
        int maleTotal = dataList.stream()
                .mapToInt(obj -> Integer.parseInt(obj.get("man").toString()))
                .sum();
        int femaleTotal = dataList.stream()
                .mapToInt(obj -> Integer.parseInt(obj.get("woman").toString()))
                .sum();
        boolean isMaleHigher = maleTotal > femaleTotal;

        String text;
        // 积极指标
        if ("1".equals(type)) {
            String fName = name + "水平";
            // 提取各等级数值 - 使用“较低”、“极低”
            int lower = levelMap.entrySet().stream()
                    .filter(entry -> entry.getKey().contains(fName + "较低"))
                    .mapToInt(Map.Entry::getValue)
                    .findFirst()
                    .orElse(0);

            int veryLow = levelMap.entrySet().stream()
                    .filter(entry -> entry.getKey().contains(fName + "极低"))
                    .mapToInt(Map.Entry::getValue)
                    .findFirst()
                    .orElse(0);

            // 有问题的人数 = 较低 + 极低
            int actualCount = lower + veryLow;
            double actualRatio = ((double) actualCount / total) * 100;
            double lowerRatio = ((double) lower / total) * 100;
            double veryLowRatio = ((double) veryLow / total) * 100;

            text = String.format(
                    "本次测评中，有%s问题的学生人数为%d人，占比为%.2f%%。其中较低水平有%d人，占比为%.2f%%；极低水平有%d人，占比为%.2f%%。性别方面，%s的%s问题的占比比%s大。",
                    fName, actualCount, actualRatio,
                    lower, lowerRatio,
                    veryLow, veryLowRatio,
                    isMaleHigher ? "男生" : "女生",
                    fName,
                    isMaleHigher ? "女生" : "男生"
            );
        } else {
            // 消极指标：轻度 + 中度 + 重度
            int light = levelMap.entrySet().stream()
                    .filter(entry -> entry.getKey().contains("轻度" + name))
                    .mapToInt(Map.Entry::getValue)
                    .findFirst()
                    .orElse(0);

            int moderate = levelMap.entrySet().stream()
                    .filter(entry -> entry.getKey().contains("中度" + name))
                    .mapToInt(Map.Entry::getValue)
                    .findFirst()
                    .orElse(0);

            int severe = levelMap.entrySet().stream()
                    .filter(entry -> entry.getKey().contains("重度" + name))
                    .mapToInt(Map.Entry::getValue)
                    .findFirst()
                    .orElse(0);

            // 有问题的人数 = 轻度 + 中度 + 重度
            int actualCount = light + moderate + severe;
            double actualRatio = ((double) actualCount / total) * 100;
            double lightRatio = ((double) light / total) * 100;
            double moderateRatio = ((double) moderate / total) * 100;
            double severeRatio = ((double) severe / total) * 100;

            text = String.format(
                    "本次测评中，有%s问题的学生人数为%d人，占比为%.2f%%。其中轻度有%d人，占比为%.2f%%；中度有%d人，占比为%.2f%%；重度有%d人，占比为%.2f%%。性别方面，%s的%s问题的占比比%s大。",
                    name, actualCount, actualRatio,
                    light, lightRatio,
                    moderate, moderateRatio,
                    severe, severeRatio,
                    isMaleHigher ? "男生" : "女生",
                    name,
                    isMaleHigher ? "女生" : "男生"
            );
        }
        return text;
    }

    @Override
    public Map<String, Object> reportInfo(ReportStudentDTO reportStudentDTO) {

        Map<String, Object> result = new HashMap<>();

        SysUser sysUser = sysUserService.selectUserById(reportStudentDTO.getUserId());
        if (sysUser == null) {
            throw new ServiceException("未找到用户信息");
        }
        Assess assess = selectAssessById(reportStudentDTO.getTaskId());
        if (assess == null) {
            throw new ServiceException("未找到任务信息");
        }

        Question question = new Question();
        question.setTaskId(assess.getId());
        question.setCommitUser(sysUser.getUserId());
        List<Question> questionList = questionService.selectQuestionList(question);
        if (!checkQuestion(questionList)) {
            throw new ServiceException("此次任务没有【抑郁】指标");
        }

        //用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("name", sysUser.getNickName());
        //0=男,1=女,2=未知
        userInfo.put("sex", "0".equals(sysUser.getSex()) ? "男" : "女");
        userInfo.put("age", "");
        userInfo.put("school", getUserSchool(sysUser.getDeptId()));
        userInfo.put("time", DateUtils.dateTime(questionList.get(0).getCommitTime()));
        Date sTime = questionList.get(0).getStartQuestionTime();
        Date eTime = questionList.get(0).getCommitTime();
        Long duration = (eTime.getTime() - sTime.getTime()) / 1000;
        userInfo.put("duration", duration + "秒");
        result.put("userInfo", userInfo);


        ReportAssessTable reportAssessTable = new ReportAssessTable();
        reportAssessTable.setUserId(reportStudentDTO.getUserId());
        reportAssessTable.setTaskId(reportStudentDTO.getTaskId());
        reportAssessTable.setAssessTableType(2L);
        result.put("negative", reportAssessTableService.selectReportAssessTableList(reportAssessTable));
        reportAssessTable.setAssessTableType(1L);
        result.put("active", reportAssessTableService.selectReportAssessTableList(reportAssessTable));


        ReportComprehensive reportComprehensive = new ReportComprehensive();
        reportComprehensive.setUserId(reportStudentDTO.getUserId());
        reportComprehensive.setTaskId(reportStudentDTO.getTaskId());
        List<ReportComprehensive> list = reportComprehensiveService.selectReportComprehensiveList(reportComprehensive);
        for (ReportComprehensive map : list) {
            if (map.getCheck() == 1L) {
                map.setMeasure(DictUtils.getDictValue("sys_check_measure", map.getName()));
                map.setDescribe(DictUtils.getDictValue("sys_check_describe", map.getName()));
            }
        }
        result.put("comprehensive", list);
        return result;
    }

    private String getComprehensive(List<ReportAssessTable> allList) {
        //获取自伤自杀等级
        String level = getPHQ9Level(allList);
        //获取其他指标等级
        boolean isCheck = getOtherLevel(allList, "正常");
        boolean isCheck1 = getOtherFalseLevel(allList, "轻度");
        //获取其他指标等级
        boolean isCheck2 = getOtherLevel(allList, "中度");
        boolean isCheck3 = getOtherFalseLevel(allList, "中度");
        boolean isCheck4 = getOtherTypeLevel(allList, "重度");
        boolean isCheck5 = getOtherSevereLevel(allList, "重度");

        if ("重度".equals(level) || isCheck5) {
            return AssessmentStatus.WARNING_LEVEL_3.getName();
        } else {
            if ("中度".equals(level) || isCheck3 || isCheck4) {
                return AssessmentStatus.WARNING_LEVEL_2.getName();
            } else {
                if ("轻度".equals(level) || isCheck1 || isCheck2) {
                    return AssessmentStatus.WARNING_LEVEL_1.getName();
                } else {
                    if ("正常".equals(level) && isCheck) {
                        return AssessmentStatus.MENTAL_HEALTH_GOOD.getName();
                    }
                }
            }
        }
//        if ("正常".equals(level) && isCheck) {
//            return AssessmentStatus.fromCheck(0L);
//        } else {
//            if ("轻度".equals(level) || isCheck1 || isCheck2) {
//                return AssessmentStatus.fromCheck(1L);
//            } else {
//                if ("中度".equals(level) || isCheck3 || isCheck4) {
//                    return AssessmentStatus.fromCheck(2L);
//                } else {
//                    if ("重度".equals(level) || isCheck5) {
//                        return AssessmentStatus.fromCheck(3L);
//                    }
//                }
//            }
//        }
        return "";
    }

    private boolean getOtherSevereLevel(List<ReportAssessTable> allList, String level) {
        for (ReportAssessTable jsonObject : allList) {
            String newLevel = jsonObject.getNewLevel();
            Long type = jsonObject.getAssessTableType();
            if (type == 2L && !level.equals(newLevel)) {
                return false;
            }
        }
        return true;
    }

    private boolean getOtherTypeLevel(List<ReportAssessTable> lists, String level) {
        for (ReportAssessTable jsonObject : lists) {
            String newLevel = jsonObject.getNewLevel();
            Long type = jsonObject.getAssessTableType();
            if (type == 2L && level.equals(newLevel)) {
                return true;
            }
        }
        return false;
    }

    private boolean getOtherFalseLevel(List<ReportAssessTable> allList, String level) {
        for (ReportAssessTable jsonObject : allList) {
            String newLevel = jsonObject.getNewLevel();
            if (!level.equals(newLevel)) {
                return false;
            }
        }
        return true;
    }

    private boolean getOtherLevel(List<ReportAssessTable> allList, String level) {
        for (ReportAssessTable jsonObject : allList) {
            String newLevel = jsonObject.getNewLevel();
            if (level.equals(newLevel)) {
                return true;
            }
        }
        return false;
    }

    private String getPHQ9Level(List<ReportAssessTable> allList) {
        String level = "";
        Iterator<ReportAssessTable> iterator = allList.iterator();
        while (iterator.hasNext()) {
            ReportAssessTable object = iterator.next();
            String itemName = object.getAssessTableName();
            if ("自伤自杀意念".equals(itemName)) {
                level = object.getNewLevel();
                iterator.remove();
                break;
            }
        }
        return level;
    }


    private boolean checkQuestion(List<Question> questionList) {
        for (Question question1 : questionList) {
            AssessTable assessTable = assessTableService.selectAssessTableById(question1.getScaleId());
            if ("PHQ-9".equals(assessTable.getShortName())) {
                return true;
            }
        }
        return false;
    }

    private ReportAssessTable getPHQ9(JSONArray jsonArray) {
        ReportAssessTable reportAssessTable = new ReportAssessTable();
        for (Object object : jsonArray) {
            JSONObject object1 = (JSONObject) object;
            if (object1.getInteger("questionId") == 9) {
                Integer phq9 = object1.getInteger("score");
                String text = "";
                switch (phq9) {
                    case 0:
                        text = "正常";
                        break;
                    case 1:
                        text = "轻度";
                        break;
                    case 2:
                        text = "中度";
                        break;
                    case 3:
                        text = "重度";
                        break;
                }
                String textStr = "正常".equals(text) ? "无" : text;
                reportAssessTable.setNewLevel(text);
                reportAssessTable.setLevel(text);
                reportAssessTable.setCheck(1L);
                reportAssessTable.setDetail("通过测试得知该生" + textStr + "自伤自杀意念");
                reportAssessTable.setAssessTableName("自伤自杀意念");
                reportAssessTable.setAssessTableType(2L);
                reportAssessTable.setName(textStr + "自伤自杀意念");
            }
        }
        return reportAssessTable;
    }

    private JSONObject getLevelByTaskLevel(Double totalScore, String taskLevelIds, Integer type) {
        JSONArray taskLevels = JSONArray.parseArray(taskLevelIds).stream()
                .sorted(Comparator.comparingDouble(e -> ((JSONObject) e).getDouble("lowestScore")).reversed())
                .collect(Collectors.toCollection(JSONArray::new));

        for (Object object : taskLevels) {
            JSONObject jsonObject = (JSONObject) object;
            Double lowestScore = jsonObject.getDouble("lowestScore");
            boolean isLowestScore = (Boolean) jsonObject.get("isLowestScore");

            if (isLowestScore ? totalScore >= lowestScore : totalScore > lowestScore) {
                jsonObject.put("check", true);
                jsonObject.put("totalScore", totalScore);
                String level = (String) jsonObject.get("level");
                if (type == 1) {
                    jsonObject.put("newLevel", getNewLevel(level));
                } else {
                    jsonObject.put("newLevel", level);
                }
                return jsonObject;
            }
        }

        //默认值
        JSONObject result = (JSONObject) taskLevels.get(taskLevels.size() - 1);
        result.put("check", true);
        result.put("totalScore", totalScore);
        String level = (String) result.get("level");
        if (type == 1) {
            result.put("newLevel", getNewLevel(level));
        } else {
            result.put("newLevel", level);
        }
        return result;
    }


    private String getNewLevel(String level) {
        // （很高、较高=正常，较低=轻度，极低=中度）
        if ("很高".equals(level) || "较高".equals(level)) {
            return "正常";
        } else if ("较低".equals(level)) {
            return "轻度";
        } else if ("极低".equals(level)) {
            return "中度";
        }
        return "";
    }

    private String getUserSchool(Long deptId) {

        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        if (sysDept == null) {
            throw new ServiceException("未找到部门");
        }
        StringBuilder sb = new StringBuilder();
        sb.append(sysDept.getDeptName()).append("-");
        return getDept(sb, sysDept.getParentId());
    }

    private String getDept(StringBuilder sb, Long parentId) {
        SysDept pDept = sysDeptService.selectDeptById(parentId);
        sb.append(pDept.getDeptName()).append("-");
        if (pDept.getParentId() != 0) {
            return getDept(sb, pDept.getParentId());
        }
        return sb.toString();
    }

}
